package cn.itcast.crawler;

import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

// HttpClient连接池
// 如果每次手动创建HttpClient对象需要资源的消耗，而且存在代码冗余
// 类似于数据库的连接池，通过这种池化技术，优化代码和效率
@SuppressWarnings("all")
public class HttpClientPoolTest {
    public static void main(String[] args) {
        // 创建HttpClient连接池对象
        PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager();

        // 设置相关的连接池参数，下面只设置连个最简单的参数
        connectionManager.setMaxTotal(100); // 最大连接对象

        connectionManager.setDefaultMaxPerRoute(10); // 每台主机的最大连接对象

        // 使用连接池对象
        doPost(connectionManager);

        doPost(connectionManager);
    }

    // 封装代码  带有参数的Post请求实现html页面的爬取
    public static void doPost(PoolingHttpClientConnectionManager connectionManager) {
        // 于之前不同的是，我们不需要手动创建HttpClient对象，而是从HttpClient池中获取
        CloseableHttpClient httpClient = HttpClients.custom().setConnectionManager(connectionManager).build();

        // 打印地址
        System.out.println(httpClient);

        // 设置url地址
        String uri = "http://yun.itheima.com/search";

        // 创建Post请求对象
        HttpPost httpPost = new HttpPost(uri);

        // Post请求体
        List<NameValuePair> params = new ArrayList<NameValuePair>(); // 创建参数容器

        params.add(new BasicNameValuePair("keys","Java")); // 添加参数

        try {
            UrlEncodedFormEntity entity = new UrlEncodedFormEntity(params,"utf8"); // 创建表单的实体对象
            httpPost.setEntity(entity); // 设置请求的实体对象
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        // 获取响应
        CloseableHttpResponse response = null;
        try {
            response = httpClient.execute(httpPost);

            if (response.getStatusLine().getStatusCode() == 200) { // 判断响应码
                String content = EntityUtils.toString(response.getEntity());
                System.out.println(content.length());
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // 防止空指针
            if (response != null) {
                try {
                    response.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            // 于之前不同的是此时我们不需要手动关闭，而是自动将HttpClient使用完之后放回HttpClient池中
        }
    }
}
